import axios from 'axios'

const request = axios.create({
    baseURL: '/api',
    timeout: 5000
})

// 添加请求拦截器
request.interceptors.request.use(
    config => {
        const savedAuth = localStorage.getItem('auth')
        if (savedAuth) {
            const { username, password } = JSON.parse(savedAuth)
            config.auth = { username, password }
        }
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

// 添加响应拦截器
request.interceptors.response.use(
    response => response,
    error => {
        if (error.response?.status === 401) {
            clearAuthCredentials()
        }
        return Promise.reject(error)
    }
)

export const setAuthCredentials = (username, password) => {
    localStorage.setItem('auth', JSON.stringify({ username, password }))
}

export const clearAuthCredentials = () => {
    localStorage.removeItem('auth')
}

export const checkAuthStatus = async () => {
    try {
        const response = await request.get('/auth/status')
        return response.data.authenticated && response.data.username
    } catch (error) {
        return false
    }
}

export default request 